package com.huilink.webmail.util.client.widgets;

public final class ValidatorFactory {
	
	private ValidatorFactory(){}

	public static final Validator createEmailValidator() {
		return new Validator() {
			private final String pattern = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$";

			public String getErrorMessage() {
				return "Invalid e-mail address.";
			}

			public boolean validate(String input) {
				return pattern.matches(input);
			}

		};
	}

	public static final Validator createMinLengthValidator(int min,
			String name) {
		final int minLength = min;

		final String fieldName = name;

		return new Validator() {

			public String getErrorMessage() {
				return fieldName + " can not be less than " + minLength
						+ " characters.";
			}

			public boolean validate(String input) {

				return (input.length() >= minLength);
			}

		};
	}

	public static final Validator createMaxLengthValidator(int max,
			String name) {
		final int maxLength = max;

		final String fieldName = name;

		return new Validator() {

			public String getErrorMessage() {
				return fieldName + " can not be more than " + maxLength
						+ " characters.";
			}

			public boolean validate(String input) {

				return (input.length() <= maxLength);
			}

		};
	}

	public static final Validator createIntegerValidator() {

		return new Validator() {

			public String getErrorMessage() {
				return "must be an integer.";
			}

			public boolean validate(String value) {
				if (value == null || value.length() == 0)
					return true;

				try {
					new Integer(value);
					return true;
				} catch (NumberFormatException e) {
					return false;
				}
			}
		};
	}
	
	public static final Validator createRangeValidator(int min, int max) {
		
		final int intMin = min;
		final int intMax = max;
		
		return new Validator() {
			
			public String getErrorMessage() {
				return "must in the range " + intMin + " through " + intMax + ".";
			}

			public boolean validate(String value) {
				boolean isValue = false;
				if (value == null || value.length() == 0)
					isValue = true;

				try {
					int intValue = new Integer(value).intValue();
					if(intValue >= intMin && intValue <= intMax && isValue)
						return true;
					return false;
				} catch (NumberFormatException e) {
					return false;
				}
			}
		};
	}
 
}
